const express = require('express');
const router = express.Router();
const db = require("../../db/index")
const upload = require("../../lib/upload")
const path = require("path")
const fs = require("fs");

// 配置三级路由
router.get('/about', (req, res) => {
  var result = [];
  var sql = `select * from companyInformation`;
  db.query(sql,(err,results)=>{
    if(err) res.send({code:0,msg:err.message});
    result = results[0];
  })
  sql = `select * from qualifications`;
  db.query(sql,(err,results)=>{
    if(err) res.send({code:0,msg:err.message});
    res.render("admin/web",{data:results[0], category:result});
  })
});

// 更新
router.get('/updateAbout', (req, res) => {
  var result = [];
  var sql = `select * from companyInformation`;
  db.query(sql,(err,results)=>{
    if(err) res.send({code:0,msg:err.message});
    if(results.length != 1){
      return res.send({code:0,msg:"查询失败"});
    }
    result = results[0];
  })
  sql = `select * from qualifications`;
  db.query(sql,(err,results)=>{
    if(err) res.send({code:0,msg:err.message});
    if(results.length == 1){
      return res.send({
        code:1,
        msg:"查询成功",
        data:results[0],
        category:result
      });
    }
    else{
      return res.send({code:0,msg:"查询失败"});
    }
  })
});

/*
briefIntroduction: '圣火昭昭，圣光耀耀，凡我弟子，喵喵喵喵， 喵喵喵喵，喵喵喵喵，喵喵喵喵，喵喵喵喵， 喵喵喵喵，喵喵喵喵，喵喵喵喵，喵喵喵喵， 喵喵喵喵
，喵喵喵喵，喵喵喵喵，喵喵喵喵， 喵喵喵喵，喵喵喵喵，喵喵喵喵，喵喵喵喵， 喵喵喵喵，喵喵喵喵，喵喵喵喵，喵喵喵喵，',
  aboutUs: '圣火昭昭，圣光耀耀，凡我弟子，同心同劳， 怜我世人，飘零无助，恩泽万物，唯光明故。 光明慈父，知义知情，启我澄心，苏我明性， 怜我世间，魔尘坌染
，除恶扬善，唯光明故， 生亦何欢，死亦何苦，熊熊圣火，焚我残躯， 十二常宝，普启诸明，妙音引路，无量净土。',
  qualification: 'CSA STAR Certification 国际认证',
  qua_img: '',
  oldqua_img: '/admin/images/资格认证1.png',
  consultationTelephone: '4000-000-100',
  businessCooperation: 'ab@abcdef.com',
  contactUs: 'abcd@abcdef.com',
  wechatOfficialAccount: 'abcd@abcdef.com',
  followUs_img: '',
  oldfollowUs_img: '/admin/images/二维码.png'
*/

router.post('/updateAbout', (req, res) => {
  const {briefIntroduction,aboutUs,qualification,qua_img,oldqua_img,
         consultationTelephone,businessCooperation,contactUs,
         wechatOfficialAccount,followUs_img, oldfollowUs_img} = req.body
  // console.log(req.body);
  var sql = `update companyInformation set briefIntroduction=?,aboutUs=?,
               consultationTelephone=?,businessCooperation=?,contactUs=?,
               wechatOfficialAccount=?`;
  db.query(sql,[briefIntroduction,aboutUs,
           consultationTelephone,businessCooperation,contactUs,
           wechatOfficialAccount],(err,results)=>{
    if (err) return res.send({code:0,msg:err.message});
    if (results.affectedRows != 1){
      res.send({code:0,msg:"修改失败"});
    }
  })
  if (req.body.followUs_img){
    sql = `update companyInformation set followUs=?`;
    db.query(sql,[req.body.followUs_img],(err,results)=>{
      if (err) return res.send({code:0,msg:err.message});
      if (results.affectedRows == 1){
        const url = path.join(__dirname, "../../static", oldfollowUs_img);
        fs.unlink(url,(error)=>{
          if (error){
            return res.send({
              code:0,
              msg:`图片删除失败:${error.message}`
            })
          }
        })
      }else{
        res.send({code:0,msg:"修改失败"});
      }
    })
  }
  // console.log(req.body);
  if (req.body.qua_img){
    sql = `update qualifications set cname=?, cimg=? where cid=1`;
    db.query(sql,[qualification, req.body.qua_img],(err,results)=>{
      if (err) return res.send({code:0,msg:err.message});
      if (results.affectedRows == 1){
        const url = path.join(__dirname, "../../static", oldqua_img);
        fs.unlink(url,(error)=>{
          if (error){
            return res.send({
              code:0,
              msg:`图片删除失败:${error.message}`
            })
          }
        })
      }else{
        res.send({code:0,msg:"修改失败"});
      }
    })
  }
  res.send({code:1,msg:"修改成功"});
});

// 网站管理中的合作伙伴管理添加
router.get('/cooperation_add', (req, res) => {
  res.render("admin/cooperation_add");
});

router.post("/cooperation_add",(req,res)=>{
  const {plogo,pname,ptxt} = req.body;
  var myDate = getNowDate();
  // console.log(myDate);
  const sql = `insert into cooperativePartner(pname,ptxt,plogo,ptime) value('${pname}','${ptxt}','${plogo}','${myDate}')`;
  // console.log(sql);
  db.query(sql,(err,results)=>{
    if (err) return res.send({code:0,msg:err.message});
    if (results.affectedRows == 1){ 
      return res.send({code:1,msg:"添加成功"});
    }else{
      return res.send({code:0,msg:"添加失败"});
    }
  })
})

// 网站管理中的合作伙伴管理列表
router.get('/cooperation_list', (req, res) => {
  res.render("admin/cooperation_list");
  // res.render("admin/cooperation_add");
});

// 网站管理中的查看合作伙伴
router.get('/cooperation_query', (req, res) => {
  let isSearch = req.query.search ? req.query.search : '';
  var count;
  const sqlCount = `select count(*) as count from cooperativePartner  where pname like "%${isSearch}%"`;
  db.query(sqlCount, (err, result) => {
    if (err) {return err.message;}
    count = result[0].count;
  });
  const { page, limit } = req.query;
  var offset = (page - 1) * limit;
  const sql = `select * from cooperativePartner where pname like "%${isSearch}%" limit ${offset},${limit}`;
  db.query(sql, (err, results) => {
    if (err) return res.send({ code: 1,msg: err.message});
    if (results.length) {
      return res.send({
        code: 0,
        msg: '数据查询成功',
        data: results,
        count: count,
      });
    } else {
      return res.send({
        code: 1,
        msg: "查询到条数为0",
      });
    }
  });
});

// 网站管理中的合作伙伴是否显示
router.get('/cooperation_updateShow', (req, res) => {
  var id = req.query.id, show = req.query.show;
  const sql = `update cooperativePartner set pshow = ${show} where pid = ${id}`;
  db.query(sql,(err,results)=>{
    // 执行sql失败
    if (err) return res.send({code:0,msg:err.message});
    if (results.affectedRows==1){
      return res.send({
        code:1,
        msg:"修改成功"
      })
    }else{
      return res.send({
        code:0,
        msg:"修改失败"
      })
    }
  })
});

router.get('/cooperation_delete',(req,res)=>{
  const {id,img} = req.query;
  const sql = `delete from cooperativePartner where pid = ${id}`;
  db.query(sql,(err,results)=>{
    if (err) return res.send({code:0,msg:err.message});
    if (results.affectedRows==1){
      // 数据库删除后删除图片
      const url = path.join(__dirname,"../../static", img);
      // console.log(url);
      fs.unlink(url,(error)=>{
        if(error){
          return res.send({
            code:0,
            msg:`图片删除失败:${error.message}`
          })
        }
        else{
          return res.send({
            code:1,
            msg:"删除成功"
          })
        }
      });
    }
    else{
      res.send({
        code:1,
        msg:"删除失败"
      })
    }
  })
})

router.get('/cooperation_update',(req,res)=>{
  const sql = `select * from cooperativePartner where pid = ${req.query.id}`;
  db.query(sql,(err,results)=>{
    if(err) return res.send({code:0,msg:err.message});
    if(results.length == 1){
      return res.send({
        code:1,
        msg:"查询成功",
        data:results[0]
      });
    }
    else{
      return res.send({code:0,msg:"查询失败"});
    }
  })
})

router.post('/cooperation_update',(req,res)=>{
  // console.log(req.body);
  const {pname,ptxt,pid,oldpimg} = req.body;
  var sql = `update cooperativePartner set pname=?,ptxt=? where pid=?`;
  db.query(sql,[pname,ptxt,pid],(err,results)=>{
    if (err) return res.send({code:0,msg:err.message});
    if (results.affectedRows != 1){
      res.send({code:0,msg:"修改失败"});
    }
  })
  if (req.body.pimg){
    sql = `update cooperativePartner set plogo=? where pid=?`;
    db.query(sql,[req.body.pimg, pid],(err,results)=>{
      if (err) return res.send({code:0,msg:err.message});
      if (results.affectedRows == 1){
        const url = path.join(__dirname, "../../static", oldpimg);
        fs.unlink(url,(error)=>{
          if (error){
            return res.send({
              code:0,
              msg:`图片删除失败:${error.message}`
            })
          } else{
            res.send({code:1,msg:"修改成功"});
          }
        })
      }else{
        res.send({code:0,msg:"修改失败"});
      }
    })
  }
  else{
    res.send({code:1,msg:"修改成功"});
  }
})

// 核心团队管理添加
router.get('/teams_add', (req, res) => {
  res.render("admin/teams_add");
});

router.post("/teams_add",(req,res)=>{
  // console.log(req.body);
  const {timg,tname,tintro,tachievementall} = req.body;
  const sql = `insert into teams(tname,tintro,timg,tachievement) value('${tname}','${tintro}','${timg}','${tachievementall.slice(0, -1)}')`;
  // console.log(sql);
  db.query(sql,(err,results)=>{
    if (err) return res.send({code:0,msg:err.message});
    if (results.affectedRows == 1){ 
      return res.send({code:1,msg:"添加成功"});
    }else{
      return res.send({code:0,msg:"添加失败"});
    }
  })
})

// 核心团队管理列表
router.get('/teams_list', (req, res) => {
  res.render("admin/teams_list");
});

// 查看核心团队
router.get('/teams_query', (req, res) => {
  let isSearch = req.query.search ? req.query.search : '';
  var count;
  const sqlCount = `select count(*) as count from teams  where tname like "%${isSearch}%"`;
  db.query(sqlCount, (err, result) => {
    if (err) {return err.message;}
    count = result[0].count;
  });
  const { page, limit } = req.query;
  var offset = (page - 1) * limit;
  const sql = `select * from teams where tname like "%${isSearch}%" limit ${offset},${limit}`;
  db.query(sql, (err, results) => {
    if (err) return res.send({ code: 1,msg: err.message});
    if (results.length) {
      return res.send({
        code: 0,
        msg: '数据查询成功',
        data: results,
        count: count
      });
    } else {
      return res.send({
        code: 1,
        msg: "查询到条数为0",
      });
    }
  });
});

// 核心团队是否显示
router.get('/teams_updateShow', (req, res) => {
  var id = req.query.id, show = req.query.show;
  const sql = `update teams set tshow = ${show} where tid = ${id}`;
  db.query(sql,(err,results)=>{
    // 执行sql失败
    if (err) return res.send({code:0,msg:err.message});
    if (results.affectedRows==1){
      return res.send({
        code:1,
        msg:"修改成功"
      })
    }else{
      return res.send({
        code:0,
        msg:"修改失败"
      })
    }
  })
});

router.get('/teams_delete',(req,res)=>{
  const {id,img} = req.query;
  const sql = `delete from teams where tid = ${id}`;
  db.query(sql,(err,results)=>{
    if (err) return res.send({code:0,msg:err.message});
    if (results.affectedRows==1){
      // 数据库删除后删除图片
      const url = path.join(__dirname,"../../static", img);
      // console.log(url);
      fs.unlink(url,(error)=>{
        if(error){
          return res.send({
            code:0,
            msg:`图片删除失败:${error.message}`
          })
        }
        else{
          return res.send({
            code:1,
            msg:"删除成功"
          })
        }
      });
    }
    else{
      res.send({
        code:1,
        msg:"删除失败"
      })
    }
  })
})

router.get('/teams_update',(req,res)=>{
  const sql = `select * from teams where tid = ${req.query.id}`;
  db.query(sql,(err,results)=>{
    var ach = 1;
    if(err) return res.send({code:0,msg:err.message});
    if(results.length == 1){
      var ach = results[0].tachievement.split(";");
      return res.send({
        code:1,
        msg:"查询成功",
        data:results[0],
        ach:ach
      });
    }
    else{
      return res.send({code:0,msg:"查询失败"});
    }
  })
})

router.post('/teams_update',(req,res)=>{
  // console.log(req.body);
  const {tname,tintro,tachievementall,tid,oldtimg} = req.body;
  // console.log(req.body);
  var sql = `update teams set tname=?,tintro=?,tachievement=? where tid=?`;
  db.query(sql,[tname,tintro,tachievementall.slice(0, -1),tid],(err,results)=>{
    if (err) return res.send({code:0,msg:err.message});
    if (results.affectedRows != 1){
      res.send({code:0,msg:"修改失败"});
    }
  })
  if (req.body.timg){
    sql = `update teams set timg=? where tid=?`;
    db.query(sql,[req.body.timg, tid],(err,results)=>{
      if (err) return res.send({code:0,msg:err.message});
      if (results.affectedRows == 1){
        const url = path.join(__dirname, "../../static", oldtimg);
        fs.unlink(url,(error)=>{
          if (error){
            return res.send({
              code:0,
              msg:`图片删除失败:${error.message}`
            })
          } else{
            res.send({code:1,msg:"修改成功"});
          }
        })
      }else{
        res.send({code:0,msg:"修改失败"});
      }
    })
  }
  else{
    res.send({code:1,msg:"修改成功"});
  }
})

function getNowDate(){
  var date = new Date();
  var sign2 = ":";
  var year = date.getFullYear() // 年
  var month = date.getMonth() + 1; // 月
  var day = date.getDate(); // 日
  var hour = date.getHours(); // 时
  var minutes = date.getMinutes(); // 分
  var seconds = date.getSeconds() //秒
  var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
  var week = weekArr[date.getDay()];
  var conment = "<br>";
  // 给一位数的数据前面加 “0”
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (day >= 0 && day <= 9) {
    day = "0" + day;
  }
  if (hour >= 0 && hour <= 9) {
    hour = "0" + hour;
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = "0" + minutes;
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = "0" + seconds;
  }
  return year + "-" + month + "-" + day + " " + hour + sign2 + minutes + sign2 + seconds;
}

// 图片上传
router.post("/upload",upload.single("file"),(req,res)=>{
  res.send({
    code:1,
    url:"/admin/uploads/" + req.file.filename
  });
})

module.exports = router;
